<template>
  <div class="app-container">
    <div class="query-form">
      <el-form
        ref="queryForm"
        :model="queryParams"
        size="small"
        inline
        label-suffix=":"
      >
        <el-form-item
          :label="$t('pick.pickNo')"
          prop="pickNo"
        >
          <el-input
            v-model="queryParams.pickNo"
            clearable
          />
        </el-form-item>
        <el-form-item
          :label="$t('pick.gmtCreated')"
          prop="gmtCreatedRange"
        >
          <el-date-picker
            v-model="queryParams.gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :range-separator="$t('to')"
            :start-placeholder="$t('beginDate')"
            :end-placeholder="$t('endDate')"
            @change="changeCreatedDateRange"
          />
        </el-form-item>
        <el-form-item
          :label="$t('pick.gmtFinished')"
          prop="gmtFinishedRange"
        >
          <el-date-picker
            v-model="queryParams.gmtFinishedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :range-separator="$t('to')"
            :start-placeholder="$t('beginDate')"
            :end-placeholder="$t('endDate')"
            @change="changeFinishedDateRange"
          />
        </el-form-item>
        <el-form-item
          :label="$t('pick.isPrinted')"
          prop="isPrinted"
        >
          <el-select
            v-model="queryParams.isPrinted"
            :placeholder="$t('pleaseSelect')"
            clearable
          >
            <el-option
              :value="0"
              :label="$t('statusLang.notPrinted')"
            />
            <el-option
              :value="1"
              :label="$t('statusLang.isPrinted')"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="handleQuery"
          >
            {{ $t("query") }}
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-refresh-left"
            @click="resetForm"
          >
            {{ $t("reset") }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="data-content">
      <el-tabs value="-1" @tab-click="handleTabClick">
        <el-tab-pane :label="$t('pick.statusAll')" name="-1" />
        <el-tab-pane :label="$t('pick.statusNew')" name="0" />
        <el-tab-pane :label="$t('pick.statusFinished')" name="1" />
      </el-tabs>
      <div class="action-bar">
        <el-button
          type="primary"
          size="small"
          @click="printedPick"
        >
          {{ $t("pick.printedPick") }}
        </el-button>
      </div>

      <div class="table-content">
        <el-table
          v-loading="dataLoading"
          border
          stripe
          :data="pickList"
          height="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            align="center"
            type="selection"
            width="55"
            fixed="left"
          />
          <el-table-column
            prop="pickNo"
            :label="$t('pick.pickNo')"
            min-width="200"
            align="center"
            fixed="left"
          >
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" @click="view(scope.row.pickNo)">
                {{ scope.row.pickNo }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="orderNum"
            :label="$t('pick.orderNum')"
            min-width="100"
            align="center"
          />
          <el-table-column
            prop="skuCount"
            :label="$t('pick.skuCount')"
            min-width="100"
            align="center"
          />
          <el-table-column
            prop="pickNum"
            :label="$t('pick.skuNum')"
            min-width="100"
            align="center"
          />
          <el-table-column
            prop="realPickNum"
            :label="$t('pick.realPickNum')"
            min-width="100"
            align="center"
          />
          <el-table-column
            prop="pickedUserName"
            :label="$t('pick.pickerName')"
            min-width="150"
            align="center"
          />
          <el-table-column
            prop="gmtCreated"
            :label="$t('pick.gmtCreated')"
            min-width="200"
            align="center"
          />
          <el-table-column
            prop="status"
            :label="$t('pick.status')"
            min-width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 0">
                {{ $t("pick.statusNew") }}
              </el-tag>
              <el-tag v-if="scope.row.status === 1" type="success">
                {{ $t("pick.statusFinished") }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="gmtFinished"
            :label="$t('pick.gmtFinished')"
            min-width="200"
            align="center"
          />
          <el-table-column
            prop="isPrinted"
            :label="$t('pick.isPrinted')"
            min-width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isPrinted === 0">
                {{ $t("statusLang.notPrinted") }}
              </el-tag>
              <el-tag v-if="scope.row.isPrinted === 1" type="success">
                {{ $t("statusLang.isPrinted") }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('operation')"
            min-width="200"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="print(scope.row.pickId)">
                {{ $t("print") }}
              </el-button>
              <el-button type="text" @click="view(scope.row.pickNo)">
                {{ $t("pick.view") }}
              </el-button>
              <el-button type="text" @click="logs(scope.row.pickId)">
                {{ $t("log") }}
              </el-button>
              <el-button type="text" @click="assignPickers(scope.row.pickId)">
                {{ $t("pick.assign") }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 页码 -->
      <el-row type="flex" justify="end" align="middle">
        <el-pagination
          :total="total"
          layout="total,sizes,prev,pager,next,jumper"
          :page-sizes="[10, 20, 30, 50, 100]"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          @current-change="pageNoChange"
          @size-change="pageSizeChange"
        />
      </el-row>
    </div>

    <el-dialog :title="$t('pick.logs')" :visible.sync="logDialogVisible" hei>
      <el-table
        border
        stripe
        :data="pickLogList"
        height="100%"
      >
        <el-table-column
          prop="operationNode"
          :label="$t('pick.optStatus')"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.operationNode === 0">
              {{ $t("pick.statusNew") }}
            </el-tag>
            <el-tag v-if="scope.row.operationNode === 1" type="success">
              {{ $t("pick.statusFinished") }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdUserName"
          :label="$t('pick.optorName')"
          width="180"
          align="center"
        />
        <el-table-column
          prop="gmtCreated"
          :label="$t('pick.optTime')"
          width="180"
          align="center"
        />
        <el-table-column
          prop="remarks"
          :label="$t('pick.remarks')"
          align="center"
        />
      </el-table>
      <!-- 页码 -->
      <el-row type="flex" justify="end" align="middle">
        <el-pagination
          :total="totalLog"
          layout="total,sizes,prev,pager,next,jumper"
          :page-sizes="[10, 20, 30, 50, 100]"
          :current-page="queryLogParams.pageNum"
          :page-size="queryLogParams.pageSize"
          @current-change="pageNoChange"
          @size-change="pageSizeChange"
        />
      </el-row>
    </el-dialog>

    <el-dialog :title="$t('pick.assignPickers')" :visible.sync="assignPickersVisible" width="40%">
      <el-form
        ref="assignPickersForm"
        :model="assignPickersRequest"
        label-suffix=":"
        label-position="right"
        label-width="150px"
      >
        <el-form-item
          :label="$t('pick.userName')"
          prop="userId"
        >
          <el-select
            v-model="userId"
            :placeholder="$t('pleaseSelect')"
            clearable
            filterable
          >
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :value="item.userId"
              :label="item.userName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignPickersVisible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" :loading="assignPickersLoading" @click="updateassignPickers">{{ $t("confirm") }}</el-button>
      </div>
    </el-dialog>

    <vue-easy-print
      ref="easyPrint"
      style="position: absolute; top: 100%"
      :one-page-row="1"
    >
      <template>
        <div v-for="(item, index) in printList" :key="index" class="printLabel">
          <el-row style="display: flex; align-items: center;">
            <el-col :span="5">
              <span style="font-weight: bold">{{ $t('pick.pickNo') }}</span>
              <br>
              <span>{{ item.pickNo }}</span>
            </el-col>
            <el-col :span="12">
              <vue-barcode
                line-color="#000"
                display-value="false"
                format="CODE128"
                font="bold"
                :value="item.pickNo"
                text-align="center"
                text-position="bottom"
                text-margin="5"
                font-size="26"
                height="60"
                width="2"
                class="barCode"
              />
            </el-col>
            <el-col :span="7">
              <span>{{ $t('pick.gmtPrinted') }}:{{ new Date().toLocaleString() }}</span>
              <br>
              <span>{{ item.printerName }}</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7">
              <span>{{ $t('pick.orderNum') }}:{{ item.orderNum }}</span>
            </el-col>
            <el-col :span="7">
              <span>{{ $t('pick.skuCount') }}:{{ item.skuCount }}</span>
            </el-col>
            <el-col :span="7">
              <span>{{ $t('pick.skuNum') }}:{{ item.pickNum }}</span>
            </el-col>
          </el-row>
          <el-divider style="margin: 20px 0" />
          <div style="margin: 0 auto; width: 800px;">
            <el-table
              :data="item.pickSkuVoList"
              height="100%"
            >
              <el-table-column
                prop="skuCode"
                :label="$t('pick.skuCode')"
                width="240"
              />
              <el-table-column
                prop="locationCode"
                :label="$t('pick.locationCode')"
                width="450"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.locationVoList.map(i => i.locationCode).join(",") }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="pickNum"
                :label="$t('pick.num')"
                width="100"
              />
            </el-table>
          </div>
        </div>
      </template>
    </vue-easy-print>
  </div>
</template>

<script>
import VueBarcode from 'vue-barcode'
import vueEasyPrint from 'vue-easy-print'
import { queryPickList, queryPickLogList, printPickBatch, assignPickers } from '@/api/business/pick/pick';
import { getAllInfo } from '@/api/upms/login';

export default {
  name: 'PickOrder',
  components: { VueBarcode, vueEasyPrint },
  data() {
    return {
      assignPickersRequest: {},
      assignPickersLoading: false,
      assignPickersVisible: false,
      userId: null,
      pickId: null,
      userList: [],
      pickList: [],
      pickLogList: [],
      printList: [],
      dataLoading: false,
      logDialogVisible: false,
      printPickLoading: false,
      queryParams: {
        pickNo: null,
        gmtCreatedRange: [],
        gmtFinishedRange: [],
        isPrinted: null,
        pageNum: 1,
        pageSize: 10,
      },
      queryLogParams: {
        pageNum: 1,
        pageSize: 10,
      },
      selectedList: [],
      total: 0,
      totalLog: 0,
    }
  },
  created() {
    this.getPickList();
    this.getUserList();
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPickList();
    },
    handleSelectionChange(rows) {
      this.selectedList = rows.map(row => row.pickId);
    },
    resetForm() {
      this.$refs['queryForm'].resetFields();
      this.queryParams.gmtCreated = [];
      this.queryParams.gmtFinished = [];
      this.queryParams.pageNum = 1;
      this.getPickList();
    },
    handleTabClick(tab, event) {
      this.queryParams.status = tab.index - 1;
      if (this.queryParams.status < 0) {
        this.queryParams.status = null;
      }
      this.queryParams.pageNum = 1;
      this.getPickList();
    },
    async getPickList() {
      this.dataLoading = true;
      await queryPickList(this.queryParams).then((res) => {
        if (!res || res.returnCode !== 10000) return;
        this.pickList = res.data.records;
        this.total = res.data.total;
      }).finally(() => {
        this.dataLoading = false
      })
    },
    async getUserList() {
      const { data } = await getAllInfo({ userName: '' })
      this.userList = data || []
    },
    pageNoChange(pageNum) {
      this.queryParams.pageNum = pageNum;
      this.getPickList();
    },
    pageSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize;
      this.getPickList();
    },
    changeCreatedDateRange(dateRange) {
      if (dateRange?.length > 0) {
        this.queryParams.gmtCreated = [dateRange[0] + ' 00:00:00', dateRange[1] + ' 23:59:59']
      } else {
        this.queryParams.gmtCreated = [];
      }
    },
    changeFinishedDateRange(dateRange) {
      if (dateRange?.length > 0) {
        this.queryParams.gmtFinished = [dateRange[0] + ' 00:00:00', dateRange[1] + ' 23:59:59']
      } else {
        this.queryParams.gmtFinished = [];
      }
    },
    async printedPick() {
      if (this.selectedList?.length > 0) {
        const { data } = await printPickBatch(this.selectedList)
        this.printList = data || {}
        this.$nextTick(() => {
          this.$refs.easyPrint.print();
          this.printList = []
        })
      }
    },
    async print(pickId) {
      const { data } = await printPickBatch([pickId])
      this.printList = data || []
      console.log(this.printList)
      this.$nextTick(() => {
        this.$refs.easyPrint.print();
        this.printList = []
      })
    },
    view(pickNo) {
      this.$router.push({ path: 'outboundOrder', query: { siCode: pickNo }})
    },
    logs(pickId) {
      this.queryLogParams.pickId = pickId
      queryPickLogList(this.queryLogParams).then((res) => {
        if (!res || res.returnCode !== 10000) return;
        this.pickLogList = res.data.records;
        this.totalLog = res.data.total;
        this.logDialogVisible = true;
      })
    },
    assignPickers(pickId) {
      this.assignPickersVisible = true;
      this.pickId = pickId;
    },
    updateassignPickers() {
      this.assignPickersLoading = true;
      assignPickers({ pickId: this.pickId, userId: this.userId }).then((res) => {
        if (!res || res.returnCode !== 10000) return
        this.$message.success({
          message: this.$t('handleSuccess')
        })
        this.getPickList();
      }).finally(() => {
        this.assignPickersLoading = false;
      })
      this.assignPickersVisible = false;
    },
  },
}
</script>

<style lang="scss" scoped>
.app-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: auto;
}

.query-form {
  padding: 18px 18px 0 18px;
  border: 1px solid #e6ebf5;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);

  .el-form-item {
    margin-right: 40px;
  }
}

.data-content {
  margin-top: 10px;
  flex: 1;
  padding: 5px 18px;
  border: 1px solid #e6ebf5;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  display: flex;
  flex-direction: column;
  min-height: 500px;
  overflow: hidden;

  .action-bar {
    padding: 0 0 11px 0;
  }

  .table-content {
    flex: 1;
    overflow: hidden;
  }
}

.printLabel {
  text-align: center;
  padding: 20px;
  page-break-after: always
}
</style>
